import { Button, View, OfficialAccount } from '@tarojs/components';
import { login, redirectTo, showModal, showLoading, hideLoading } from '@tarojs/taro';
import Layout from '../../components/Layout';
import XList from '../../components/XList';
import baseService from '../../utils/baseService';

const Auth = () => {
  const onGetUserInfo = (e) => {
    console.log(e);
    if (e.detail.errMsg.includes('deny')) {
      showModal({
        title: '请允许授权',
        content: '允许授权后才可以使用',
        showCancel: false,
        confirmText: '我知道了'
      });
    } else if (e.detail.errMsg.includes('ok')) {
      const {
        detail: { encryptedData, errMsg, iv }
      } = e;
      showLoading({ title: '操作中' });
      login().then(({ code }) => {
        baseService
          .post('/uaa/newwxminidoctor/updateunionid', {
            code: code,
            encryptedData: encryptedData,
            iv: iv
          })
          .then(({ status, message, data }) => {
            if (status === 1) {
              hideLoading();
              redirectTo({ url: '/pages/auth/login' });
            } else {
              showModal({
                title: '授权失败',
                content: message,
                showCancel: false,
                confirmText: '重试'
              });
            }
          })
          .catch(() => {
            hideLoading();
          });
      });
    }
  };

  return (
    <Layout isShowHeader={true} isFullScreen={false}>
      <XList isCustomize={true}>接下来的操作需要您授权！</XList>
      <View>
        <Button type="primary" openType="getUserInfo" onGetUserInfo={onGetUserInfo}>
          点击进行微信授权
        </Button>
      </View>
      <View style={{ padding: '15px 10px', marginTop: '30px' }}>
        <OfficialAccount></OfficialAccount>
      </View>
    </Layout>
  );
};

Auth.config = {
  navigationBarTitleText: '微信授权',
  navigationStyle: 'custom'
};

export default Auth;
